package com.ssm.controller;

import com.ssm.entity.Employee;
import com.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/getall")
    @ResponseBody
    public List<Employee> getall(Model model){
        return userService.getall(null);
    }

    @GetMapping("/add")
    public String add(){
        return "/user/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public int add(@RequestBody Employee employee){
        int count = userService.add(employee);
        return count;
    }

    @GetMapping("/del/{id}")
    public String del(@PathVariable Long id){
       userService.del(id);
       return "redirect:/users";
    }

    @GetMapping("/update/{id}")
    public String update(@PathVariable Long id,Model model){
        model.addAttribute("user",userService.get(id));
        return "user/update";
    }

    @PostMapping("/update")
    public String update(Employee employee){
        int count = userService.update(employee);
        if(count==1){
            return "redirect:/users";
        }
        return "user/update";
    }
}
